package org.finesys.common.feign.core;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import feign.RequestInterceptor;
import feign.RequestTemplate;

/**
 * feign请求头参数处理
 */
public class FeignHeaderRequestInterceptor implements RequestInterceptor, Ordered {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //如果不存在，则无需拷贝请求头信息
        if (servletRequestAttributes == null) {
            return;
        }
        HttpServletRequest request = servletRequestAttributes.getRequest();
        Enumeration<String> requestHeaderNames = request.getHeaderNames();
        assert requestHeaderNames != null;
        while (requestHeaderNames.hasMoreElements()) {
            String headerName = requestHeaderNames.nextElement();
            String value = request.getHeader(headerName);
            if(HttpHeaders.CONTENT_LENGTH.toLowerCase().equalsIgnoreCase(headerName)||HttpHeaders.COOKIE.toLowerCase().equalsIgnoreCase(headerName)){
                continue;
            }
            if(HttpHeaders.CONTENT_TYPE.toLowerCase().equalsIgnoreCase(headerName)){
                continue;
            }
            requestTemplate.header(headerName, value);
        }
        requestTemplate.header(HttpHeaders.CONNECTION, "close");
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
